import * as actionTypes from '../actionType';
import Storage from '@/utils/Storage';

const baseReducer = ({ baseState, type, callback }) => (
	state = baseState,
	action
) => {
	switch (action.type) {
	case type:
		if (action.type === actionTypes.AXIOS_ENQUEUE){
			if (!action.data){
				state.forEach(cancel =>cancel());
				state =[];
			} else {
				state = [...state,action.data];
			}
			return [...state];
		}
		callback && callback(type, action.data);
		return action.data;
	default:
		return state;
	}
};

// 用户信息
const user = baseReducer(
	{
		baseState : Storage.get(actionTypes.USER, 1) || {},
		type : actionTypes.USER,
		callback : (key, data) => {
			Storage.set(key, data, 1);
		}
	}
);

// 菜单列表
const menu = baseReducer(
	{
		baseState : Storage.get(actionTypes.TREE_LIST, 1) || [],
		type : actionTypes.TREE_LIST,
		callback : (key, data) => {
			Storage.set(key, data, 1);
		}
	}
);

// 权限列表
const permissions = baseReducer(
	{
		baseState : Storage.get(actionTypes.PERMISSIONS, 1) || [],
		type : actionTypes.PERMISSIONS,
		callback : (key, data) => {
			Storage.set(key, data, 1);
		}
	}
);

// 请求取消
const axiosCancel = baseReducer(
	{
		baseState : [],
		type : actionTypes.AXIOS_ENQUEUE
	}
);

export default {
	user,
	menu,
	permissions,
	axiosCancel
};
